<?php
/**
 * Created by PhpStorm.
 * User: moquan
 * Date: 2019/3/14
 * Time: 18:02
 */

namespace app\admin\controller;


use app\admin\model\AdminMenu;
use app\admin\model\AdminRole;
use app\admin\model\MenuModel;
use app\admin\validate\IDVali;
use app\admin\validate\MenuVali;
use app\admin\validate\UserVali;
use app\lib\exception\ParamException;
use think\Db;
use think\Log;
use think\Response;

class Menu extends Base {
    function index(){
        $data = MenuModel::order('sort','asc')->select()->toArray();
        $menu = MenuModel::getMenuTreeData( $data, 0 );
        $html = MenuModel::getPageMenuTreeHtml( $menu );

        $this->assign('li', $html);
        return $this->fetch();
    }

    function jsonMenuData() {
        $req = $this->request->param();
        $checked = array();
        if ( isset($req['role_id']) ) {
            $roleInfo = AdminRole::get( array( 'role_id' => $req['role_id'] ) );
            $checked = $roleInfo['menu_auth'];
        }


        $data = MenuModel::order('sort','asc')->select()->toArray();
        $menu = MenuModel::getMenuTreeData( $data, 0, $checked );
        Response::create( $menu, 'json')->send();
    }

    // 添加
    function add () {
        $req = (new MenuVali())->goCheck('other');
        $id = $req['id'];

        // 菜单数据
        $condition['menu_type'] = array('neq', 'btn');
        $data = MenuModel::where($condition)->order('sort','asc')->select()->toArray();
        $menu = MenuModel::getMenuTreeData( $data, 0 );
        $html = MenuModel::getSelectMenuTreeHtml( $menu, 0, $id );

        // 菜单类型
        $types = MenuModel::getMenuTypes();

        // 角色列表
        $roles = AdminRole::getAdminRoleByMenuId();

        // 动态数据(页页初始化值)
        $data = array( 'menu_type' => 'left' );

        $this->assign('data', $data);
        $this->assign('types', $types);
        $this->assign('roles', $roles);
        $this->assign('options', $html);

        return $this->fetch();
    }

    function doAdd() {
        $req = (new MenuVali())->goCheck();

        $res = MenuModel::add($req);
        if ( true === $res ) {
            return json( array( 'error_code' => 1, 'msg' => '操作成功', 'data' => $req, 'debug' => $res ) );
        }

        return json( array( 'error_code' => 40000, 'msg' => '操作失败', 'data' => $res, 'debug' =>'' ) );

    }

    // 修改
    function edit () {
        $req = (new MenuVali())->goCheck('other');

        // 菜单数据
        $condition['menu_type'] = array('neq', 'btn');
        $data = MenuModel::where($condition)->order('sort','asc')->select()->toArray();
        $menu = MenuModel::getMenuTreeData( $data, 0 );
        $html = MenuModel::getSelectMenuTreeHtml( $menu, 0, $req['parent_id'] );

        // 菜单类型
        $types = MenuModel::getMenuTypes();

        // 角色列表
        $roles['list'] = AdminRole::getAdminRoleByMenuId()->toArray();
       /* $roles['selected'] = AdminRole::all(function ($query) use ($req){
            $query->where("LOCATE('\"".$req['id']."\"',menu_auth)>0");
        })->toArray();*/
        $roleIds = AdminRole::getRoleMenuAuth( $req['id'] )->toArray();
        foreach ($roleIds as $val ) {
            $roles['selected'][] = $val['role_id'];
        }
        // 本条数据
        $data = MenuModel::getAdminMenuById( $req['id'] );
//        dump($roleIds);
        $this->assign('data', $data);
        $this->assign('options', $html);
        $this->assign('types', $types);
        $this->assign('roles', json_encode($roles));
//        Log::write( 111,'print');

        return $this->fetch();
    }

    function doEdit() {
        $req = (new MenuVali())->goCheck();
        $reqRoles = $req['roles'];
        $menuId = $req['id'];

        // 所有角色
        $roles = AdminRole::select();
        // 所有菜单
        $menu = MenuModel::select()->toArray();

        $newMenuAuth = array();
        foreach ( $roles as $key => $role ) {
            $isSet = in_array( $role->role_id, $reqRoles );
            $isDel = !$isSet && in_array( $menuId, (array)$role->menu_auth);

            if ( $isSet || $isDel ) {
                $menuAuth = (array)$role->menu_auth;

                // 当前菜单id的所有(父子及自己)
                $parents = MenuModel::getParents( $menu, $menuId);
                $childrens = MenuModel::getChildren( $menu, $menuId);

                // 设置(增加|更新)
                if ( $isSet ) {
                    $allMenu = array_column( array_merge( (array)$parents, (array)$childrens ), 'id');
                    $roleMenuAuth = array_unique( array_merge($menuAuth, $allMenu) );
                }

                // 删除
                if ( $isDel ) {
                    $allMenu = array_column( $childrens, 'id' );
                    $self = array_pop($parents);
                    $res = MenuModel::getSpecialSiblings($menu, $self['parent_id']);
                    if ( $res ) {
                        $allMenu = array_column( array_merge($res, $childrens), 'id' );
                    }
                    array_push($allMenu, $req['id'] );
                    $roleMenuAuth = array();
                    foreach ( $menuAuth as $key => $val ) {
                        if ( !in_array($val, $allMenu ) ) {
                            $roleMenuAuth[] = $val;
                        }
                    }
                }

                if ( $roleMenuAuth ) {
                    $temp = implode(',', array_values($roleMenuAuth));
                    $finalMenuAuth = explode(',', $temp);
                } else {
                    $finalMenuAuth = '';
                }


                $newMenuAuth[] = array(
                    'role_id' => $role->id,
                    'menu_auth' => $finalMenuAuth
                );
            }

        }

        $Menu = new MenuModel();
        $Role = new AdminRole();
        $Role->saveAll( $newMenuAuth );
        $Menu->allowField(true)->save( $req, array('id' => $req['id']) );

        return json( array( 'error_code' => 1, 'msg' => '操作成功', 'data' => $req ) );
    }

    /*
     * 设置角色菜单权限
     * @param int $role_id 角色ID
     * @param string $menu_auth 菜单权限
     *
     * */
    function setRoleMenuAuth( $role_id, $menu_auth ) {
        $menu = MenuModel::select()->toArray();
        $parents = MenuModel::getParents( $menu, $menu_auth);
        $childrens = MenuModel::getChildren( $menu, $menu_auth);
        $allMenu = array_column( array_merge( (array)$parents, (array)$childrens ), 'id');

        $role = AdminRole::get($role_id);
        $menuAuth = (array)$role->menu_auth;

        $roleMenuAuth = array_unique( array_merge($menuAuth, $allMenu) );
        $temp = implode(',', array_values($roleMenuAuth));
        return explode(',', $temp);
    }

    // 删除
    function disabled() {
        $req = (new IDVali())->goCheck();

        $Menu = new MenuModel();
        $Menu->allowField(true)->save( array( 'status' => 0 ), array('id' => $req['id']) );

        return json( array( 'error_code' => 1, 'msg' => '操作成功', 'data' => $req ) );
    }

    // 删除
    function del() {
        $req = (new IDVali())->goCheck();

        MenuModel::destroy( $req['id'] );

        return json( array( 'error_code' => 1, 'msg' => '操作成功', 'data' => $req ) );
    }

}